<template>
  <div class="document-container">
    <el-card class="upload-card">
      <template #header>
        <div class="card-header">
          <span>文档管理</span>
          <el-upload
            class="upload-button"
            :action="'api/documents/upload'"
            :headers="headers"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            accept=".pdf,.jpg,.jpeg,.png"
          >
            <el-button type="primary">
              <el-icon><Upload /></el-icon>
              上传文档
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持 PDF、JPG、PNG 格式，文件大小不超过 10MB
              </div>
            </template>
          </el-upload>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="documents"
        style="width: 100%"
        row-key="id"
        border
        stripe
      >
        <el-table-column prop="fileName" label="文件名" min-width="200">
          <template #default="scope">
            <el-icon><Document /></el-icon>
            <span style="margin-left: 8px">{{ scope.row.fileName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="uploadTime" label="上传时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.uploadTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="startChat(scope.row)"
            >
              <el-icon><ChatDotRound /></el-icon>
              开始问答
            </el-button>
            <el-popconfirm
              title="确定要删除这个文档吗？"
              @confirm="handleDelete(scope.row)"
            >
              <template #reference>
                <el-button
                  type="danger"
                  link
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Document, Upload, ChatDotRound, Delete } from '@element-plus/icons-vue'
import axios from '../utils/axios'

const router = useRouter()
const loading = ref(false)
const documents = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const headers = {
  Authorization: `Bearer ${localStorage.getItem('token')}`
}

// 获取文档列表
const getDocuments = async () => {
  loading.value = true
  try {
    const { data } = await axios.get('/documents', {
      params: {
        page: currentPage.value - 1,
        size: pageSize.value
      }
    })
    documents.value = data

    total.value = data.totalElements
  } catch (error) {
    ElMessage.error('获取文档列表失败')
  } finally {
    loading.value = false
  }
}

// 上传成功处理
const handleUploadSuccess = (response) => {
  ElMessage.success('上传成功')
  getDocuments()
}

// 上传失败处理
const handleUploadError = () => {
  ElMessage.error('上传失败')
}

// 上传前检查
const beforeUpload = (file) => {
  const isValidType = file.type === 'application/pdf' || 
                     file.type === 'image/jpeg' || 
                     file.type === 'image/png'
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isValidType) {
    ElMessage.error('只能上传PDF/JPG/PNG文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  return true
}

// 开始问答
const startChat = (document) => {
  router.push({
    name: 'DocumentQA',
    params: { id: document.id }
  })
}

// 删除文档
const handleDelete = async (document) => {
  try {
    await axios.delete(`/documents/${document.id}`)
    ElMessage.success('删除成功')
    getDocuments()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  getDocuments()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getDocuments()
}

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleString()
}

onMounted(() => {
  getDocuments()
})
</script>

<style scoped>
.document-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.upload-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-button {
  margin-left: auto;
}

.el-upload__tip {
  color: #666;
  font-size: 12px;
  margin-top: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-table .cell) {
  white-space: nowrap;
}

:deep(.el-upload-list) {
  max-height: 200px;
  overflow-y: auto;
}
</style> 